package com.deer.wms.base.system.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.deer.wms.base.system.model.Item.*;
import com.deer.wms.base.system.model.erp.ErpOutConstant;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.constant.Constants;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.ExcelUtil;
import com.deer.wms.project.root.util.RandomNo;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import static com.deer.wms.project.root.util.CollectionUtils.convertMap;

/**
 * @author guo
 * @date 2019/11/19
 */
@Api(description = "物料信息api接口")
@RestController
@RequestMapping("/item/infos")
public class ItemInfoController {

    private Random rand;

    {
        try {
            rand = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private ItemInfoService itemInfoService;
    /**
     * 质检标识导入
     * @return   [返回类型说明]
     * @exception/throws [异常类型] [异常说明]
     * @see    [类、类#方法、类#成员]
     * @since  [起始版本]
     * @deprecated
     */
    @ApiOperation(value = "质检标识导入", notes = "质检标识导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @PostMapping("/importQcState")
    public Result importQcState(ItemImport excel, @ApiIgnore @User CurrentUser currentUser) throws IOException {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        if (excel.getModel() == null){
            throw new ServiceException(CommonCode.PARAMETERISNULL,"参数为空");
        }

        List<ItemQcData> soExcelData = ExcelUtil.readExcel(excel.getModel(), ItemQcData.class, 0);
        //查物料表
        List<ItemInfo> list = itemInfoService.list();
        //转换成map
        Map<String, ItemInfo> itemInfoMap = convertMap(list, ItemInfo::getItemCode);
        List<ItemInfo> listAdd=new ArrayList<>();
        for(ItemQcData data:soExcelData){
            if(itemInfoMap.containsKey(data.getItemCode())){
                ItemInfo item=itemInfoMap.get(data.getItemCode());
                item.setQcTacticCode("1");
                listAdd.add(item);
            }
        }
        //批量更新
         itemInfoService.updateBatchById(listAdd);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "新增itemInfo以及itemInfo列表", notes = "新增itemInfo以及itemInfo列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/insert")
    public Result add(@RequestBody ItemInfo itemInfo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
//        int rValue = (int) (this.rand.nextDouble() * (999 - 100 + 1)) + 100;
//        String itemCode = "IM" + RandomNo.createNo() + '-' + rValue;
//        itemInfo.setItemCode(itemCode);
        itemInfoService.save(itemInfo);
        return ResultGenerator.genSuccessResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/delete")
    @ApiOperation(value = "删除itemInfo信息", notes = "删除itemInfo信息")
    public Result delete(Integer id, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        itemInfoService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @PostMapping("/update")
    @ApiOperation(value = "更新itemInfo信息", notes = "更新itemInfo信息")
    public Result update(@RequestBody ItemInfo itemInfo) {
        //修改增加质检标识
        if(itemInfo.getIsQcState()){
            itemInfo.setQcTacticCode("1");
        }else {
            itemInfo.setQcTacticCode("");
        }
        itemInfoService.updateById(itemInfo);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        ItemInfo itemInfo = itemInfoService.getById(id);
        return ResultGenerator.genSuccessResult(itemInfo);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/list")
    @ApiOperation(value = "物料查询列表", notes = "物料查询列表")
    public Result list(ItemInfoCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        criteria.setPageNum(criteria.getPageNum()<=0?0:criteria.getPageNum() - 1);
//        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<ItemInfoDto> list = itemInfoService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);

        pageInfo.setTotal(itemInfoService.findCount(criteria));
        pageInfo.setPageNum(criteria.getPageNum()+1);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 启用物料
     *
     * @param itemCode
     * @return
     */
    @ApiOperation(value = "启用物料", notes = "启用物料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true)
    })
    @Authority
    @GetMapping("/enable")
    public Result enable(String itemCode, @ApiIgnore @User CurrentUser currentUser) {
        itemInfoService.modifyItemState(itemCode, Constants.ITEM_ENABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 停用物料
     *
     * @param itemCode
     * @return
     */
    @ApiOperation(value = "停用物料", notes = "停用物料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true)
    })
    @Authority
    @GetMapping("/disable")
    public Result disable(String itemCode, @ApiIgnore @User CurrentUser currentUser) {
        itemInfoService.modifyItemState(itemCode, Constants.ITEM_DISABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "新增or修改物料")
    @PostMapping("/saveItemInfoList")
    public Result saveItemList(Map<String,Object> hashMap){
        itemInfoService.saveItemList(hashMap);
        return ResultGenerator.genSuccessResult();
    }

}
